import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/bean/file_path_entity.dart';
import 'package:flutter_app/manager/AppSetInfoManager.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/ui/home/home/home_view.dart';
import 'package:flutter_app/ui/mine/mine/mine_view.dart';
import 'package:flutter_app/ui/mine/password_change/password_change_view.dart';
import 'package:flutter_app/ui/msg/msg/msg_list_view.dart';
import 'package:flutter_app/ui/queue/queue_view.dart';
import 'package:flutter_app/utils/DialogUtils.dart';
import 'package:flutter_app/utils/device_info_utils.dart';
import 'package:flutter_app/utils/path_utils.dart';
import 'package:flutter_app/utils/sp_utils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/values/CommonParam.dart';
import 'package:flutter_app/values/MyColors.dart';
import 'package:flutter_app/widget/dragable.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';
import 'package:get/state_manager.dart';
import 'package:image_pickers/image_pickers.dart';

import '../../r.dart';
import 'main_state.dart';

class MainLogic extends GetxController {
  final MainState state = MainState();

  // 存储 子页面 相当于activity中的fragment
  List<Widget> fragment = <Widget>[];

  late List<String> titles;

  // 正常图标
  late List normalIcon;

  // 选中图标
  late List selectedIcon;

  @override
  void onInit() {
    super.onInit();
    titles = [
      '首页',
      '消息',
      '我的',
    ];
    normalIcon = [
      R.assetsImgBar1,
      R.assetsImgBar3,
      R.assetsImgBar5,
    ];
    selectedIcon = [
      R.assetsImgBar2,
      R.assetsImgBar4,
      R.assetsImgBar6,
    ];

    fragment.add(HomePage(title: "首页"));
    fragment.add(MsgListPage(title: "消息"));
    fragment.add(MinePage(title: "个人中心"));
  }

  @override
  void onReady() {
    super.onReady();

    getNoticeReadCount();


    ///初始化时 弹出弹出框 必须加上Future.delayed
    Future.delayed(Duration.zero, () async {
      /// 添加强制修改密码逻辑
      if (await UserInfoManager().getInitPassword()) {
        goToPasswordChangePage();
      }
    });

    // 全局悬浮
    dragableItem(
      onTap: () {
        Get.to(() => QueuePage());
      },
      size: 50.r,
      child: Container(
        width: 50.r,
        height: 50.r,
        decoration: BoxDecoration(
          color: MyColors.FFC30802,
          borderRadius: BorderRadius.circular(25.r),
          boxShadow: [
            BoxShadow(
                color: MyColors.FFC20E0B.withAlpha(80),
                offset: const Offset(1, 2)),
            BoxShadow(
                color: MyColors.FFC20E0B.withAlpha(60),
                offset: const Offset(2, 3)),
          ],
        ),
        child: Icon(
          Icons.cloud_upload_rounded,
          color: Colors.white,
          size: 25.r,
        ),
      ),
    );

    checkAuthDevice();
  }

  /// 是否需要 跳转修改密码界面
  goToPasswordChangePage() {
    dialogUtils.show(
      context: Get.context!,
      title: "提示",
      content: "请重置初始化密码",
      callbackOk: () {
        Get.to(() => PasswordChangePage(title: "修改密码",));
      },
    );
  }

  /// 文件下载
  Future<bool> downLoad(String urlPath, String fileName) async {
    Response response = await Api.downLoad(urlPath, fileName);
    if (response.statusCode == 200) {
      toast.show("文件下载成功");
      return true;
    } else {
      toast.show("文件下载失败");
      return false;
    }
  }

  /// 多文件上传接口
  Future<List<FilePathEntity>?> uploadFiles(
    List<Media> imagesList, {
    Function? uploadProgress,
  }) async {
    List<FilePathEntity>? filePathEntity;
    // 解决 Bad state: Can't finalize a finalized MultipartFile. 问题
    // Dio使用post提交表单请求时，每次重新提交时，data参数都需要传入一个新的表单对象。
    List<MultipartFile> multipartFiles = [];
    imagesList.forEach((element) {
      String name = PathUtils.getName(element.path!);
      if (element.dateTime != null && element.address != null) {
        name = "${UserInfoManager().getUserName()}-${element.dateTime}-${element.address}." + name.split(".").last;
      }
      multipartFiles.add(MultipartFile.fromFileSync(element.path!, filename: name));
    });
    ResultData resultData = await Api.uploadFiles(multipartFiles,
        onSendProgress: uploadProgress != null
            ? (int sent, int total) {
                uploadProgress.call(sent, total);
              }
            : null);

    if (resultData.isSuccess) {
      List<dynamic> list = jsonDecode(jsonEncode(resultData.data['data']));
      filePathEntity = list.map((e) => FilePathEntity.fromJson(e)).toList();
      return filePathEntity;
    } else {
      toast.show(resultData.data["message"]);
    }
    return null;
  }

  /// 获取消息未读数量
  Future<void> getNoticeReadCount() async {
    ResultData resultData = await Api.getNoticeReadCount({});

    if (resultData.isSuccess) {
      state.noticeReadCount.value = resultData.data['data'];
      if (state.noticeReadCount.value >= 99) {
        state.noticeReadCount.value = 99;
      }
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 更新消息已读
  Future<void> updateNoticeRead(String? id) async {
    Map<String, dynamic> param = {
      "id": id,
    };
    ResultData resultData = await Api.updateNoticeRead(param);
    if (resultData.isSuccess) {
      readNotice();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 读了一条消息
  void readNotice() {
    state.noticeReadCount--;
  }

  /// 标记全不已读
  void readAllNotice() {
    state.noticeReadCount.value = 0;
  }

  /// 获取清单和关联上报问题列表
  Future<void> checkAuthDevice() async {

    // 状态码为0 表示不开启权限
    if (AppSetInfoManager().getPinState() == "1") {
      state.pinPutState.value = true;
      await sp.setBool(CommonParam.PIN_PUT_STATE, true);
      return;
    }

    Map<String, dynamic> param = {
      "id": await DeviceInfoUtils().getDeviceId,
    };
    ResultData resultData = await Api.checkAuthDevice(param);
    if (resultData.isSuccess) {
      String data = resultData.data["data"];
      // 0无授权记录1已授权2授权已解除
      if (data == "1") {
        state.pinPutState.value = true;
        await sp.setBool(CommonParam.PIN_PUT_STATE, true);
      } else {
        state.pinPutState.value = false;
        await sp.setBool(CommonParam.PIN_PUT_STATE, false);
      }
    }
  }

  @override
  void onClose() {
    super.onClose();
  }
}
